package signal;

final class Consumer implements Runnable {

    private String name;
    private Pot pot;

    public Consumer(Pot pot, String name) {
        this.name = name;
        this.pot = pot;
    }

    @Override
    public void run() {
        //儿子不停的吃馒头
        while (true) {
            if (Pot.COUNT >= 100 && pot.getPot().size() == 0) {
                break;
            }
            //注意：lock和unlock一定是成对出现。
            pot.getLock().lock();
            pot.eatCake(this.name);
            pot.getLock().unlock();
            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

final class Producer implements Runnable {
    private Pot pot;

    public Producer(Pot pot) {
        this.pot = pot;
    }

    @Override
    public void run() {
        //妈妈不停的做馒头
        while (true) {

            if (Pot.COUNT >= 100) {
                System.out.println("100个馒头做完了，妈妈线程结束！");
                break;
            }

            pot.getLock().lock();
            pot.makeCake();

            pot.getLock().unlock();

            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

public class ProducerConsumeGameLockDemo {

    public static void main(String[] args) {
        Pot pot = new Pot();
        Producer mother = new Producer(pot);
        Consumer bigSon = new Consumer(pot, "大林");
        Consumer smallSon = new Consumer(pot, "小林");

        Thread motherTh = new Thread(mother);
        Thread bigSonTh = new Thread(bigSon);
        Thread smallSonTh = new Thread(smallSon);

        //分别启动三个
        motherTh.start();
        bigSonTh.start();
        smallSonTh.start();

        //等待三个线程都结束
        try {
            motherTh.join();
            bigSonTh.join();
            smallSonTh.join();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        pot.showResult();
    }

}
